﻿if (typeof Axis == "undefined") Axis = {};
if (typeof Axis.Admin == "undefined") Axis.Admin = {};

Axis.Admin.ListProject = {
    Init: function () {
        var thisObj = this;
        thisObj.Grid.Init();
        thisObj.EventClick();
        $("button").button();
        var cmaskdate = new CMaskDate({
            dateTimePicker: true

        });
        cmaskdate.Init($("#txtEndDate,#txtStartDate"));
        thisObj.DropdownChecklist.Init();
    },
    DropdownChecklist: {
        Instance: null,
        Init: function () {
            $("#FormEdit,#FormFilter").show();
            var thisObj = this;
            thisObj.Instance = new CDropDownCheckList({ width: 200, maxDropHeight: 310, firstItemChecksAll: true });
            thisObj.Instance.Init("#FormEdit select[multiple]");
            $("#FormEdit,#FormFilter").hide();
        },
        Clear: function () {
            var thisObj = this;
            $("#FormEdit select[multiple]").find("option").removeAttr("selected");
            thisObj.Refresh();
        },
        Refresh: function () {
            var thisObj = this;
            if (thisObj.Instance) {
                thisObj.Instance.Refresh();
            }
        }
    },
    Grid: {
        ID: "#GridContents",
        PagesID: "#GridPages",
        Init: function () {
            var thisObj = this;
            var options = {
                url: 'Service/ProjectService.ashx?Action=GET',
                datatype: "json",
                colNames: [
                    'ID', 'Mã', 'Tên', 'Tóm tắt', 'Nội dung', 'Nhóm', 'UserGroupID', 'Hình 1', 'Hình 2',
                    'Ngày bắt đầu', 'Ngày kết thúc', 'Last Update', 'Ngày tạo', 'Trạng thái', 'Điểm', 'dataRequired', 'Tags', 'Hinh thức chạy', 'Xử lý'
                ],
                colModel: [
                    { name: 'ID', index: 'ID', width: 50, frozen: true, hidden: true, key: true, hidedlg: true },
                    { name: 'Code', index: 'Code', width: 100, frozen: true, hidden: true, hidedlg: true },
                    { name: 'Name', index: 'Name', width: 150, frozen: true },
                    { name: 'Summary', index: 'Summary', width: 250, hidden: true },
                    { name: 'Description', index: 'Description', width: 250, hidden: true },
                    { name: 'UserGroupName', index: 'UserGroupName', width: 200 },
                    { name: 'UserGroupID', index: 'UserGroupID', width: 50, hidden: true, hidedlg: true },
                    { name: 'Image1', index: 'Image1', width: 50, align: 'center' },
                    { name: 'Image2', index: 'Image2', width: 50, hidden: true, hidedlg: true },

                    {
                        name: 'StartDate', index: 'StartDate',
                        formatter: 'date', formatoptions: {
                            srcformat: "m/d/Y H:i",
                            newformat: "d/m/Y H:i"
                        },
                        width: 120, align: 'center'
                    },
                    {
                        name: 'EndDate', index: 'EndDate',
                        formatter: 'date', formatoptions: {
                            srcformat: "m/d/Y H:i",
                            newformat: "d/m/Y H:i"
                        },
                        width: 120, align: 'center'
                    },
                    { name: 'LastUpdatedDateTime', index: 'LastUpdatedDateTime', width: 120, align: 'center', hidden: true },
                    { name: 'CreatedDateTime', index: 'CreatedDateTime', width: 120, align: 'center', hidden: true },
                    { name: 'Status', index: 'Status', width: 55, align: 'center', hidden: true },
                    { name: 'Mark', index: 'Mark', width: 55, align: 'center' },
                    { name: 'RequiredField', index: 'RequiredField', width: 55, align: 'center', hidden: true },
                     { name: 'Tags', index: 'Tags', width: 55, align: 'center', hidden: true },
                      { name: 'RunType', index: 'Tags', width: 105, align: 'center' },
                    { name: 'Action', index: 'Action', width: 55, align: 'center' }
                ],
                afterInsertRow: function (rowid, aData, addData) {

                    var RunType = $.string.Format("<img class='imgAction' src='../../Images/16x16/publish.png' onclick=\"PublishProject({0} , 2)\"/>", rowid);
                    if (aData.Status == "2")
                        RunType = $.string.Format("<img class='imgAction' src='../../Images/16x16/runtest.png' onclick=\"PublishProject({0} , 0)\"/>", rowid);
                    $(thisObj.ID).jqGrid('setCell', rowid, 'RunType', RunType);
                },
                gridComplete: function () {
                    $('.imgProjectImage').tooltip({
                        delay: 0,
                        track: true,
                        showURL: false,
                        bodyHandler: function () {
                            return $("<img/>").attr("src", this.src);
                        }
                    });
                },
                onCellSelect: function (rowid, iCol, cellcontent, e) {

                },
                onSelectRow: function (rowid, status, e) {

                },
                ondblClickRow: function (rowid, iRow, iCol, e) {

                },
                subGrid: true,
                subGridRowExpanded: function (subgrid_id, row_id) {
                    var subgrid_table_id, pager_id;
                    subgrid_table_id = subgrid_id + "_t";
                    pager_id = "p_" + subgrid_table_id;
                    $("#" + subgrid_id).html("<table id='" + subgrid_table_id + "' class='scroll'></table><div id='" + pager_id + "' class='scroll'></div>");
                    $("#" + subgrid_table_id).jqGrid({
                        url: "../Gift/Service/GiftService.ashx",
                        mtype: 'POST',
                        postData: { Action: "GET", ProjectID: row_id },
                        datatype: "json",
                        colNames: [
                            'ID', 'Code', 'Tên quà', 'Hình', 'Mô tả',
                            'Mark', 'Amount', 'Manufactor', 'Số lượng', 'Thuộc nhóm', 'GroupID'
                        ],
                        colModel: [
                            { name: 'ID', index: 'ID', width: 50, hidden: true, frozen: true },
                            { name: 'Code', index: 'Code', width: 100, frozen: true, hidden: true },
                            { name: 'Name', index: 'Name', width: 150, frozen: true },
                            { name: 'Image', index: 'Image', width: 100 },
                            { name: 'Description', index: 'Description', width: 250, hidden: true },
                            { name: 'Mark', index: 'Mark', width: 100, hidden: true },
                            { name: 'Amount', index: 'Amount', width: 50, hidden: true },
                            { name: 'Manufactor', index: 'Manufactor', width: 50, hidden: true },
                            { name: 'Quantity', index: 'Quantity', width: 100, align: 'center' },
                            { name: 'GroupName', index: 'GroupName', width: 150 },
                            { name: 'GroupID', index: 'GroupID', width: 50, hidden: true, hidden: true, hidedlg: true }
                        ],
                        rowNum: 20,
                        sortname: 'num',
                        sortorder: "asc",
                        height: '100%',
                        gridComplete: function () {
                            $('.imgGiftImage').tooltip({
                                delay: 0,
                                track: true,
                                showURL: false,
                                bodyHandler: function () {
                                    return $("<img/>").attr("src", this.src);
                                }
                            });
                        }
                    });
                },
                multiselect: true,
                height: 'auto',
                rownumbers: true,
                autowidth: true,
                //forceFit: true,
                shrinkToFit: false,
                rowNum: 20,
                pager: thisObj.PagesID
            };
            thisObj.GridObj = new CGrid(options);
            thisObj.GridObj.Init(thisObj.ID);
            thisObj.GridObj.NavGrid();
            thisObj.GridObj.FrozenColumns();
        },
        Reload: function () {
            var thisObj = this;
            if (thisObj.GridObj)
                thisObj.GridObj.ReloadGrid();
        },
        SelectRow: function () {
            var thisObj = this;
            if (thisObj.GridObj) {
                return thisObj.GridObj.SelectRow();
            }
            return null;
        }
    },
    DialogEdit: {
        ID: "#FormEdit",
        Dialog: null,
        Init: function (action, opts) {
            var thisObj = this;
            thisObj.ClearForm();
            if (thisObj.Dialog) {
                thisObj.Dialog.Open();
            }
            else {
                thisObj.Dialog = new CDialog({
                    title: "Sửa dự án",
                    width: 800,
                    position: {
                        my: 'top',
                        at: 'top'
                    },
                    open: function () {
                        var config = {
                            width: 790,
                            height: 40,
                            toolbar: 'MyToolbar',
                            filebrowserBrowseUrl: '/ckfinder/ckfinder.html',
                            filebrowserImageBrowseUrl: '/ckfinder/ckfinder.html?type=Images',
                            filebrowserFlashBrowseUrl: '/ckfinder/ckfinder.html?type=Flash',
                            filebrowserUploadUrl: '/ckfinder/core/connector/aspx/connector.aspx?command=QuickUpload&type=Files',
                            filebrowserImageUploadUrl: '/ckfinder/core/connector/aspx/connector.aspx?command=QuickUpload&type=Images',
                            filebrowserFlashUploadUrl: '/ckfinder/core/connector/aspx/connector.aspx?command=QuickUpload&type=Flash'
                        };
                        if (!CKEDITOR.instances["txtDescription"]) {
                            CKEDITOR.replace("txtDescription", config);
                        }
                        if (!CKEDITOR.instances["txtSummary"]) {
                            config.height = 40;
                            CKEDITOR.replace("txtSummary", config);
                        }
                    }
                });
                thisObj.Dialog.Init(thisObj.ID);
            }
            var buttonText = "";
            switch (action) {
                case "INSERT":
                    thisObj.Dialog.SetTitle("Thêm dự án");
                    $(thisObj.ID).find("[data-role='INSERT']").show();
                    $(thisObj.ID).find("#txtLoginName").focus();
                    buttonText = "Add";
                    break;
                case "UPDATE":
                    thisObj.Dialog.SetTitle("Sửa: " + opts.Name);
                    $.each(opts, function (key, value) {
                        switch (key) {
                            case "Image1":
                            case "Image2":
                                value = $(value).attr("FileName") || "";
                                $(thisObj.ID).find("[data-field=" + key + "]").val(value);
                                break;
                            case "Description":
                                if (CKEDITOR && CKEDITOR.instances["txtDescription"])
                                    CKEDITOR.instances["txtDescription"].setData(value);
                                break;
                            case "Summary":
                                if (CKEDITOR && CKEDITOR.instances["txtSummary"])
                                    CKEDITOR.instances["txtSummary"].setData(value);
                                break;
                            case 'Tags':
                                var dataRequiredField = value.split(",");
                                if (dataRequiredField) {
                                    $.each(dataRequiredField, function (index, _value) {
                                        if (_value) {
                                            var $selector = $("select#ddlTags");
                                            var $option = $selector.find($.string.Format("option[value='{0}']", _value));
                                            $option.attr("selected", "selected");
                                        }
                                    });
                                    Axis.Admin.ListProject.DropdownChecklist.Refresh();
                                }
                                break;
                            case "RequiredField":
                                var dataRequiredField = value.split(",");
                                if (dataRequiredField) {
                                    $.each(dataRequiredField, function (index, _value) {
                                        if (_value) {
                                            var $selector = $("select#ddlInfoRequire");
                                            var $option = $selector.find($.string.Format("option[value='{0}']", _value));
                                            $option.attr("selected", "selected");
                                        }
                                    });
                                    Axis.Admin.ListProject.DropdownChecklist.Refresh();
                                }
                                break;
                            default:
                                $(thisObj.ID).find("[data-field=" + key + "]").val(value);
                        }

                    });
                    $.Ajax({
                        url: '../Gift/Service/GiftService.asmx/GetGift',
                        type: 'POST',
                        data: { pProjectID: opts.ID },
                        success: function (data, textStatus, jqXHR) {
                            if (data) {
                                data = $(data).find("string").text();
                                data = eval("(" + data + ")");
                                if (data) {
                                    $.each(data, function (index, item) {
                                        var giftID = item.ID;
                                        var giftGroupID = item.ID;
                                        var giftName = item.Name;
                                        var giftQuantity = item.Quantity;
                                        var ret = $.string.Format('<div class="gift_item" data-field="Gift" GiftID="{0}" GiftQuantity="{2}"><span class="gift_remove ui-icon ui-icon-close"></span><span class="gift_edit ui-icon ui-icon-pencil"></span><span class="gift_name">{1}</span><span class="gift_quantity">{2}</span></div>',
                                            giftID, giftName, giftQuantity);
                                        $("#gift_items").append(ret);
                                    });
                                }
                            }
                        },
                        beforeSend: function (jqXHR, settings) {
                        },
                        error: function (jqXHR, textStatus, errorThrown) {
                        },
                        complete: function (XMLHttpRequest, textStatus) {
                        }
                    });
                    buttonText = "Update";
                    break;
            }
            var buttons = [
                        {
                            text: buttonText,
                            click: function (e) {
                                Axis.Admin.ListProject.Update(action, opts);
                                thisObj.Close();
                            }
                        },
                        {
                            text: "Cancel",
                            click: function (e) {
                                thisObj.Close();
                            }
                        }

            ];
            $(thisObj.ID).dialog('option', 'buttons', buttons);
        },
        Open: function () {
            var thisObj = this;
            if (thisObj.Dialog) {
                thisObj.Dialog.Open();
            }
        },
        Close: function () {
            var thisObj = this;
            if (thisObj.Dialog) {
                thisObj.Dialog.Close();
            }
        },
        ClearForm: function () {
            $("#FormEdit").find("[data-field]").each(function () {
                var $this = $(this);
                $this.val("");
                if ($this.is("select")) {
                    var value = $this.find("option[Default-Value='1']").attr("value");
                    $this.val(value);
                }

            });
            $("#txtScreening").val(3);
            $("#FormEdit").find("[data-role='INSERT']").hide();
            $("#gift_items").html("");
            Axis.Admin.ListProject.DropdownChecklist.Clear();
        }
    },
    Update: function (type, opts) {
        var thisObj = this;
        var data = {};
        switch (type) {
            case "INSERT":
            case "UPDATE":
                $("#FormEdit").find("[data-field]").each(function () {
                    var $this = $(this);
                    if ($this.attr("data-field")) {
                        var key = $this.attr("data-field");
                        var value = $this.val();
                        if ($this.attr('type') == 'checkbox') {
                            if ($this.is(':checked'))
                                value = 1;
                        }
                        if (key == "Gift") {
                            var giftID = $this.attr("giftID");
                            var giftQuantity = $this.attr("GiftQuantity");
                            key = "Gift_" + giftID;
                            value = giftQuantity;
                        }

                        if ($this.attr("role") == "datepicker") {
                            value = $.CFormat.FormatDate(value, "yyyy/MM/dd HH:mm", "vi-VN", "en-US");
                        }
                        if (key == "RequiredField") {
                            if (value && $.isArray(value)) {
                                value = value.join(",");
                            }
                        }
                        if (key == "Tags") {
                            if (value && $.isArray(value)) {
                                value = value.join(",");
                            }
                        }
                        data[key] = value;
                    }
                });
                break;
            case "DELETE":
                data.ID = opts.ID;
                break;
        }
        if (CKEDITOR && CKEDITOR.instances["txtDescription"])
            data.Description = CKEDITOR.instances["txtDescription"].getData();
        if (CKEDITOR && CKEDITOR.instances["txtSummary"])
            data.Summary = CKEDITOR.instances["txtSummary"].getData();
        data.Action = type;
        if (typeof USER_ID != "undefined") {
            data.UserID = USER_ID;
            data.SecrectToken = SECRECT_TOKEN;
        }
        $.Ajax({
            url: 'Service/ProjectService.ashx',
            type: 'POST',
            data: data,
            success: function (data, textStatus, jqXHR) {
                if (data) {
                    data = eval("(" + data + ")");
                    if (data.IsSuccessfull) {
                        thisObj.Grid.Reload();
                    }
                }
            },
            beforeSend: function (jqXHR, settings) {
            },
            error: function (jqXHR, textStatus, errorThrown) {
            },
            complete: function (XMLHttpRequest, textStatus) {
            }
        });
    },
    DialogFilter: {
        Init: function () { }
    },
    EventClick: function () {
        var thisObj = this;
        $("#imgUserAdd").click(function () {
            thisObj.DialogEdit.Init("INSERT");
        });
        $("#imgUserEdit").click(function () {
            var rowData = thisObj.Grid.SelectRow();
            if (rowData && rowData.ID)
                thisObj.DialogEdit.Init("UPDATE", rowData);
            else alert("Please Select Row");
        });
        $("#imgUserDel").click(function () {
            var rowData = thisObj.Grid.SelectRow();
            if (rowData && rowData.ID) {
                $.CAlert.Confirm({
                    Title: "Xóa dự án",
                    Content: $.string.Format("Bạn có chắc muốn xóa dự án: [{0}].", rowData.Name)
                }, function (isOK) {
                    if (isOK)
                        thisObj.Update("DELETE", rowData);
                });
            }
            else {
                $.CAlert.Alert({
                    Title: "Xóa dự án",
                    Content: "Vui lòng chọn dự án cần xóa."
                });
            }

        });
        $("#imgUserFilter").click(function () {
            thisObj.DialogFilter.Init();
        });
        $("#btnSelectImg").click(function () {
            var finder = new CKFinder();
            finder.resourceType = 'Images';
            finder.startupPath = "Images:/z/";
            finder.selectActionFunction = function (fileUrl) {
                $('#txtImage').val(fileUrl);
            };
            finder.popup();
        });
        $("#btnSelectImg2").click(function () {
            var finder = new CKFinder();
            finder.resourceType = 'Images';
            finder.selectActionFunction = function (fileUrl) {
                $('#txtImage2').val(fileUrl);
            };
            finder.popup();
        });
        $("#btn_AddGift").click(function () {
            var giftDialog = new CDialog({
                title: "Quà tặng",
                open: function () {
                    $("#FormGift").find("#txt_GiftQuantity").val("");
                    $("#FormGift").find("#ddlGiftGroup").removeAttr("disabled");
                    $("#FormGift").find("#ddlGift").removeAttr("disabled");

                },
                buttons: [
                    {
                        text: "Thêm quà",
                        click: function () {
                            var giftName = $("#FormGift").find("#ddlGift option:selected").text();
                            var giftGroupID = $("#FormGift").find("#ddlGiftGroup").val();
                            var giftID = $("#FormGift").find("#ddlGift").val();
                            var giftQuantity = $("#FormGift").find("#txt_GiftQuantity").val();
                            var isExisted = false;
                            $("#gift_items").find(".gift_item").each(function () {
                                var _gid = $(this).attr("GiftID");
                                if (_gid == giftID) {
                                    $.CAlert.Alert({
                                        Title: "Quà tặng",
                                        Content: "Quà tặng này đã tồn tại. Vui lòng chọn quà khác."
                                    });
                                    isExisted = true;
                                }
                            });
                            if (isExisted)
                                return false;
                            if (!giftQuantity) {
                                alert("Chưa chọn số lượng !!!");
                                return false;
                            }
                            var ret = $.string.Format('<div class="gift_item" data-field="Gift" GiftID="{0}" giftGroupID="{1}" GiftQuantity="{2}"><span class="gift_remove ui-icon ui-icon-close"></span><span class="gift_edit ui-icon ui-icon-pencil"></span><span class="gift_name">{3}</span><span class="gift_quantity">{2}</span></div>',
                                giftID, giftGroupID, giftQuantity, giftName);
                            $("#gift_items").append(ret);
                            $(this).dialog("close");
                        }
                    },
                    {
                        text: "Đóng",
                        click: function () {
                            $(this).dialog("close");
                        }
                    }
                ]
            });
            giftDialog.Init("#FormGift");
        });
        $(".gift_item .gift_remove").live("click", function () {
            var $this = $(this);
            var giftName = $this.parent().find(".gift_name").text();
            $.CAlert.Confirm({
                Title: "Xóa quà tặng",
                Content: $.string.Format("Bạn có chắc muốn xóa quà tăng: [{0}].", giftName)
            }, function (isOK) {
                if (isOK)
                    $this.parent().remove();
            });
        });
        $(".gift_item .gift_edit").live("click", function () {
            var $parent = $(this).parent();
            var giftID = $parent.attr("giftID");
            var giftQuantity = $parent.attr("giftQuantity");
            var giftGroupID = $("#FormGift").find("#ddlGift option[value='" + giftID + "']").attr("groupid");
            var giftDialog = new CDialog({
                title: "Quà tặng",
                open: function () {
                    $("#FormGift").find("#ddlGiftGroup").val(giftGroupID).attr("disabled", "disabled");
                    $("#FormGift").find("#ddlGift").val(giftID).attr("disabled", "disabled");
                    $("#FormGift").find("#txt_GiftQuantity").val(giftQuantity).focus();
                },
                buttons: [
                    {
                        text: "Cập nhật",
                        click: function () {
                            var giftName = $("#FormGift").find("#ddlGift option:selected").text();
                            var giftID = $("#FormGift").find("#ddlGift").val();
                            var giftQuantity = $("#FormGift").find("#txt_GiftQuantity").val();

                            var ret = $.string.Format('<div class="gift_item" data-field="Gift" GiftID="{0}" GiftQuantity="{2}"><span class="gift_remove ui-icon ui-icon-close"></span><span class="gift_edit ui-icon ui-icon-pencil"></span><span class="gift_name">{1}</span><span class="gift_quantity">{2}</span></div>',
                                giftID, giftName, giftQuantity);
                            $(ret).insertAfter($(".gift_item[GiftID='" + giftID + "']"));
                            $(".gift_item[GiftID='" + giftID + "']").eq(0).remove();
                            $(this).dialog("close");
                        }
                    },
                    {
                        text: "Đóng",
                        click: function () {
                            $(this).dialog("close");
                        }
                    }
                ]
            });
            giftDialog.Init("#FormGift");
        });
        $("#ddlGiftGroup").change(function () {
            var groupID = $(this).val();
            $("#ddlGift").find("option").hide();
            $("#ddlGift").find("option[groupid='" + groupID + "']").show();
            $("#ddlGift").find("option[groupid='" + groupID + "']").each(function (index) {
                $(this).html();
                var _val = $(this).attr("value");
                if (index == 0) {
                    $("#ddlGift").val(_val);
                }

            });

        }).trigger("change");
    },
    ChangeStatus: function (projectID, status) {
        var thisObj = this;
        var pData = { ProjectID: projectID, Status: status };
        $.ajax({
            url: 'Service/ManagerQuestionService.asmx/ChangeStatus',
            type: 'POST',
            data: JSON.stringify(pData),
            cache: false,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (pData, textStatus, jqXHR) {
                $("body").removeClass('iMarkets-overlay-modal');
                var data = eval("(" + pData.d + ")");
                if (data) {

                    if (data.IsSuccessfull) {
                        thisObj.Grid.Reload();
                    }
                }
            },
            beforeSend: function (jqXHR, settings) {
                $("#ddlGiftLottory").html('');
                $("#ddlGift").html('');
                $("body").addClass('iMarkets-overlay-modal');
            },
            error: function (jqXHR, textStatus, errorThrown) {
                //  overlay.Hide();
                $("body").removeClass('iMarkets-overlay-modal');
            },
            complete: function (XMLHttpRequest, textStatus) {
                // overlay.Hide();
            }
        });
    }


};
$(function () {
    Axis.Admin.ListProject.Init();
});
function ShowEdit(rowID) {
    var thisObj = Axis.Admin.ListProject;
    var rowData = $(thisObj.Grid.ID).jqGrid('getRowData', rowID);
    if (rowData && rowData.ID)
        thisObj.DialogEdit.Init("UPDATE", rowData);
}
function FormatGridDescription(cellvalue, options, rowObject) {
    if (cellvalue.indexOf("project_desc_panel") == -1) {
        return '<div class="project_desc_panel">' + cellvalue + '</div>';
    }
    else
        return cellvalue;

}
function PublishProject(projectID, status) {
    var thisObj = Axis.Admin.ListProject;
    var message = "Bạn có muốn chuyển dự án này sang chế độ test không ?";
    if (status == 0)
        message = "Bạn có muốn chuyển dự án này sang chế độ chạy thực tế không ?";
    $.CAlert.Confirm({
        Title: "Điểu chỉnh dự án",
        Content: message
    }, function (isOK) {
        if (isOK)
            thisObj.ChangeStatus(projectID, status);
    });
}